package org.piggy.core.filter.loadbalance.rule;

import org.piggy.common.config.ServiceInstance;
import org.piggy.common.enums.ResponseCode;
import org.piggy.common.exception.PiggyException;
import org.piggy.core.context.GatewayContext;
import org.piggy.core.manager.DynamicConfigManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

public class RandomLoadBalanceRule implements LoadBalanceGatewayRule {

    private RandomLoadBalanceRule(){}

    private static final RandomLoadBalanceRule randomLoadBalanceRule = new RandomLoadBalanceRule();

    public static LoadBalanceGatewayRule getInstance (){
        return randomLoadBalanceRule;
    }

    @Override
    public ServiceInstance choose(GatewayContext context) {
        // serviceName = serviceId:version
        Set<ServiceInstance> set = DynamicConfigManager.getInstance().getServiceInstanceByServiceName(context.getRule().getServiceName(), context.isGray());
        if(set.isEmpty()){
            throw new PiggyException(ResponseCode.SERVICE_INSTANCE_NOT_FOUND);
        }else{
            List<ServiceInstance> instances = new ArrayList<>(set);
            int index = ThreadLocalRandom.current().nextInt(instances.size());
            return instances.get(index);
        }
    }
}
